import axios from 'axios';
import { getStore, setStore } from './storage';
import { router } from '../router/index';
import { Message } from 'view-design';
import Cookies from 'js-cookie';
let base = '/zwz';

axios.defaults.timeout = 60000;

// 添加请求日志
axios.interceptors.request.use(config => {
    console.log('发送请求:', {
        url: config.url,
        method: config.method,
        params: config.params,
        data: config.data
    });
    
    // 从cookie中获取token
    const token = Cookies.get('ZWZ_TOKEN');
    if (token) {
        config.headers['accessToken'] = token;
    }
    return config;
}, err => {
    console.error('请求配置错误:', err);
    Message.error('请求超时');
    return Promise.reject(err);
});

// 添加响应日志
axios.interceptors.response.use(response => {
    console.log('收到响应:', {
        status: response.status,
        data: response.data,
        headers: response.headers
    });
    
    const data = response.data;

    // 如果后端返回的是Result对象
    if (data && typeof data === 'object' && 'success' in data) {
        return {
            success: data.success,
            result: data.result,
            message: data.message || 'OK',
            code: data.code || 200,
            timestamp: data.timestamp
        };
    }

    // 处理其他响应格式
    switch (data.code) {
        case 401:
            console.warn('认证失败，需要重新登录');
            Cookies.set('userInfo', '');
            setStore('accessToken', '');
            if (router.history.current.name != "login") {
                if (data.message !== null) {
                    Message.error(data.message);
                } else {
                    Message.error("未知错误，请重新登录");
                }
                router.push('/login');
            }
            break;
        case 403:
            console.warn('权限不足');
            if (data.message !== null) {
                Message.error(data.message);
            } else {
                Message.error("未知错误");
            }
            break;
        case 500:
            console.error('服务器错误');
            if (data.message !== null) {
                Message.error(data.message);
            } else {
                Message.error("未知错误");
            }
            break;
        default:
            return {
                success: true,
                result: data,
                message: data.message || 'OK',
                code: 200,
                timestamp: Date.now()
            };
    }

    return data;
}, (err) => {
    console.error('响应错误:', err);
    if (err.response) {
        console.error('错误响应详情:', {
            status: err.response.status,
            data: err.response.data,
            headers: err.response.headers
        });
    }
    Message.error(err.toString());
    return Promise.reject(err);
});

export const getRequest = (url, params) => {
    console.log(`发起GET请求: ${base}${url}`, params);
    const token = Cookies.get('ZWZ_TOKEN');
    return axios({
        method: 'get',
        url: `${base}${url}`,
        params: params,
        headers: {
            'accessToken': token
        }
    }).catch(error => {
        console.error(`GET请求失败: ${base}${url}`, error);
        throw error;
    });
};

export const postRequest = (url, params) => {
    const token = Cookies.get('ZWZ_TOKEN');
   
    
    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params,
        headers: {
            'Content-Type': 'application/json',
            'accessToken': token
        }
    });
};

export const putRequest = (url, params) => {
    const token = Cookies.get('ZWZ_TOKEN');
    return axios({
        method: 'put',
        url: `${base}${url}`,
        data: params,
        headers: {
            'Content-Type': 'application/json',
            'accessToken': token
        }
    });
};

export const postBodyRequest = (url, params) => {
    const token = Cookies.get('ZWZ_TOKEN');
    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params,
        headers: {
            'accessToken': token
        }
    });
};

export const getNoAuthRequest = (url, params) => {
    return axios({
        method: 'get',
        url: `${base}${url}`,
        params: params
    });
};

export const postNoAuthRequest = (url, params) => {
    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params,
        transformRequest: [function (data) {
            let ret = '';
            for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
            }
            ret = ret.substring(0, ret.length - 1);
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
};

// 添加 DELETE 请求方法
export const deleteRequest = (url, params) => {
  return axios({
    method: 'delete',
    url: `${base}${url}`,
    params: params
  })
}

export const postRequestWithParams = (url, params) => {
    const token = Cookies.get('ZWZ_TOKEN');
    const formData = new URLSearchParams();
    
    // 处理参数，支持普通参数和数组参数
    if (params) {
        Object.keys(params).forEach(key => {
            const value = params[key];
            if (Array.isArray(value)) {
                // 如果是数组，则多次append同名参数
                value.forEach(item => formData.append(key, item));
            } else if (value !== undefined && value !== null) {
                // 如果是普通值且不为空，则直接append
                formData.append(key, value);
            }
        });
    }

    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: formData,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'accessToken': token
        }
    });
};
